<template>
  <div class="">
    三级分类维护
    <el-switch v-model="draggable" active-text="开启拖拽"> </el-switch>
    <el-button v-if="draggable" @click="batchSave">批量保存</el-button>
    <el-button type="danger" @click="batchDelete">批量删除</el-button>

    <el-tree
      :data="menu"
      :props="defaultProps"
      :show-checkbox="true"
      node-key="catId"
      :expand-on-click-node="false"
      :default-expanded-keys="expandedKey"
      :draggable="draggable"
      :allow-drop="allowDrop"
      @node-drop="handleDrop"
      ref="menuTree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            type="text"
            v-if="node.level <= 2"
            size="mini"
            @click="() => append(data)"
          >
            Append
          </el-button>
          <el-button type="text" size="mini" @click="edit(data)">
            edit
          </el-button>
          <el-button
            type="text"
            v-if="node.childNodes.length == 0"
            size="mini"
            @click="() => remove(node, data)"
          >
            Delete
          </el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog
      :title="dialogName"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="category">
        <el-form-item label="分类名">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="计量单位">
          <el-input
            v-model="category.productUnit"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: "",
  props: {},
  components: {},
  data() {
    return {
      pCid: [],
      draggable: false,
      updateNodes: [],
      maxLevel: 1,
      dialogType: "", //edit add
      dialogName: "",
      menu: [],
      expandedKey: [],
      dialogVisible: false,
      category: {
        name: "",
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        catId: null,
        icon: "",
        productUnit: "",
      },
      defaultProps: {
        children: "children",
        label: "name",
      },
    };
  },
  methods: {
    batchDelete() {
      let childNodes = this.$refs.menuTree.getCheckedNodes();

      let ids = [];
      
      let parentIds = [];

      for (let i = 0; i < childNodes.length; i++) {
        ids.push(childNodes[i].catId);
        parentIds.push(childNodes[i].parentCid);
      }
      console.log(childNodes);
      console.log(ids);

      this.$confirm(
        `此操作将批量删除菜单【${ids}】, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        this.$http({
          url: this.$http.adornUrl("/product/category/delete"),
          method: "post",
          data: this.$http.adornParams(ids, false),
        }).then(({ data }) => {
          console.log("删除成功!");
          this.$message({
            type: "success",
            message: "菜单删除修改成功!",
          });
          this.expandedKey = parentIds;
          this.getMenus();
        });
      });
    },
    batchSave() {
      this.$http({
        url: this.$http.adornUrl("/product/category/update/sort"),
        method: "post",
        data: this.$http.adornParams(this.updateNodes, false),
      }).then(({ data }) => {
        console.log("修改成功!");
        this.$message({
          type: "success",
          message: "菜单顺序修改成功!",
        });
        console.log("pCid", this.pCid);
        this.expandedKey = this.pCid;
        this.updateNodes = [];
        this.getMenus();
      });
    },
    getMenus() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get",
      }).then(({ data }) => {
        console.log("成功获取到菜单数据。。。", data.data);
        this.menu = data.data;
      });
    },
    allowDrop(draggingNode, dropNode, type) {
      this.maxLevel = 1;

      console.log("allowDrop", draggingNode, dropNode, type);

      this.countNodeLevel(draggingNode);

      if (this.maxLevel == 1) {
        this.maxLevel = draggingNode.level;
      }

      console.log("深度：", this.maxLevel);

      let draggingLevel = this.maxLevel - draggingNode.level + 1;

      console.log("最终层数：", draggingLevel);

      if (type == "inner") {
        console.log("inner");
        return draggingLevel + dropNode.level <= 3;
      } else {
        console.log("!=inner");
        return draggingLevel + dropNode.parent.level <= 3;
      }
    },
    handleDrop(draggingNode, dropNode, dropType, ev) {
      console.log("handleDrop: ", draggingNode, dropNode, dropType);

      //1.获取当前最新id
      let pCid = 0;
      let siblings = null;
      if (dropType == "inner") {
        pCid = dropNode.data.catId;
        siblings = dropNode.childNodes;
      } else {
        pCid =
          dropNode.parent.data.catId == undefined
            ? 0
            : dropNode.parent.data.catId;
        siblings = dropNode.parent.childNodes;
      }

      this.pCid.push(pCid);

      //2.获取最新顺序
      for (let i = 0; i < siblings.length; i++) {
        if (siblings[i].data.catId == draggingNode.data.catId) {
          let catLevel = draggingNode.level;
          if (siblings[i].level != draggingNode.level) {
            this.catLevel = siblings[i].level;
          }

          //3.获取最新层级
          this.updateChildNodeLevel(siblings[i].childNodes);

          this.updateNodes.push({
            catId: siblings[i].data.catId,
            sort: i,
            parentCid: pCid,
            catLevel: catLevel,
          });
        } else {
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i });
        }
      }

      console.log(this.updateNodes);
    },
    updateChildNodeLevel(node) {
      if (node != null && node.length > 0) {
        for (let i = 0; i < node.length; i++) {
          this.updateNodes.push({
            catId: node[i].data.catId,
            catLevel: node[i].level,
          });

          this.updateChildNodeLevel(node[i].childNodes);
        }
      }
    },
    countNodeLevel(node) {
      if (node.childNodes != null && node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          if (node.childNodes[i].catLevel > this.maxLevel) {
            this.maxLevel = node.childNodes[i].level;
          }
          this.countNodeLevel(node.childNodes[i]);
        }
      }
    },
    addCategory() {
      console.log("提交的分类数据", this.category);

      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornParams(this.category, false),
      }).then(({ data }) => {
        console.log("添加成功！");
        this.$message({
          type: "success",
          message: "添加成功!",
        });
        this.dialogVisible = false;
        this.expandedKey = [this.category.parentCid];
        this.getMenus();
      });
    },
    editCategory() {
      console.log("修改的分类数据", this.category);
      var { catId, name, icon, productUnit } = this.category;

      this.$http({
        url: this.$http.adornUrl("/product/category/update"),
        method: "post",
        data: this.$http.adornParams({ catId, name, icon, productUnit }, false),
      }).then(({ data }) => {
        console.log("修改成功！");
        this.$message({
          type: "success",
          message: "修改成功!",
        });
        this.dialogVisible = false;
        this.expandedKey = [this.category.parentCid];
        this.getMenus();
      });
    },
    submitData() {
      if (this.dialogType == "add") {
        this.addCategory();
      }

      if (this.dialogType == "edit") {
        this.editCategory();
      }
    },
    append(data) {
      this.category.name = "";
      this.dialogVisible = true;
      this.dialogType = "add";
      this.dialogName = "添加";

      this.category.catId = null;
      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel * 1 + 1;
      this.category.icon = data.icon;
      this.category.productUnit = data.productUnit;

      console.log("add", data);
    },
    edit(data) {
      this.category.name = "";
      console.log("要修改的数据：", data);
      this.dialogType = "edit";
      this.dialogName = "修改";
      this.dialogVisible = true;

      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "get",
      }).then(({ data }) => {
        console.log("要回显的数据", data);
        this.category.name = data.data.name;
        this.category.catLevel = data.data.catLevel;
        this.category.icon = data.data.icon;
        this.category.productUnit = data.data.productUnit;
        this.category.catId = data.data.catId;
        this.category.parentCid = data.data.parentCid;
      });
    },
    remove(node, data) {
      var ids = [data.catId];

      this.$confirm(
        `此操作将永久删除该菜单【${data.name}】, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornParams(ids, false),
          })
            .then(({ data }) => {
              console.log("刪除成功！");
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getMenus();
              this.expandedKey = [node.parent.data.catId];
            })
            .catch(() => {
              this.$message({
                type: "error",
                message: "刪除失敗！",
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });

      console.log("remove", node, data);
    },
  },
  computed: {},
  watch: {},
  created() {
    this.getMenus();
  },
  mounted() {},
  beforeDestroy() {},
};
</script>
<style  scoped>
</style>